"""
__author__ = '霍格沃兹测试开发学社'
__desc__ = '更多测试开发技术探讨，请访问：https://ceshiren.com/t/topic/15860'
"""
from flask_jwt_extended import create_access_token

from dao.user_dao import UserDao
from do.user_do import UserDo
from server import jwt

user_dao = UserDao()


class UserService:

    def get(self, user_id):
        # 通过id查询数据
        return user_dao.get(user_id)

    def list(self):
        # 返回所有
        return user_dao.list()

    def save(self, user_do: UserDo):
        # 保存之前先查询数据是否存在
        # 存在返回false,不存在则进行新增
        user = self.get_by_name(user_do.username)
        if not user:
            return user_dao.save(user_do)
        else:
            return False

    def update(self, user_do: UserDo):
        # 用例存在则进行更新修改，否则返回错误
        user = self.get(user_do.id)
        if not user:
            return False
        else:
            return user_dao.update(user_do)

    def delete(self, user_id):
        # 用户存在则进行删除，否则返回错误
        user = self.get(user_id)
        if not user:
            return False
        else:
            return user_dao.delete(user_id)

    def get_by_name(self, username):
        return user_dao.get_by_name(username)

    def create_access_token(self, user_do):
        return create_access_token(identity=user_do)

    @jwt.user_lookup_loader
    def user_lookup_callback(self, _jwt_header, jwt_data):
        # 获取 username
        username = jwt_data["sub"]["username"]
        # 返回通过 username 查询用户的结果
        return self.get_by_name(username)
